package com.sanley.piss.web.service;


import com.gitee.dreamkaylee.shiro.util.SubjectUtil;
import com.sanley.piss.mapper.RoleAndResourceRelationMapper;
import com.sanley.piss.mapper.RoleMapper;
import com.sanley.piss.mapper.UserAndRoleRelationMapper;
import com.sanley.piss.model.ServiceImpl;
import com.sanley.piss.model.StringUtil;
import com.sanley.piss.model.exceptionUtil.exception.ServiceException;
import com.sanley.piss.model.po.Role;
import com.sanley.piss.model.po.RoleAndResourceRelation;
import com.sanley.piss.model.po.UserAndRoleRelation;
import com.sanley.piss.model.vo.LoginUser;
import com.sanley.piss.web.service.mapper.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Create By  on 2021/3/6.
 *
 * @author 张凯大天才
 */
@Service
@Primary
@Transactional(rollbackFor = ServiceException.class)
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Autowired
    private RoleAndResourceRelationMapper roleAndResourceRelationMapper;

    @Autowired
    private UserAndRoleRelationMapper userAndRoleRelationMapper;


    /**
     * 创建新角色
     */
    @Override
    public void insert(Role role) {
        String name = role.getName();
        if (StringUtil.isNotNull(baseMapper.seletByName(name))) {
            throw new ServiceException("名称" + role.getName() + "已经存在");
        }
        if (StringUtil.isNotNull(baseMapper.seletByCode(role.getCode()))) {
            throw new ServiceException("编码" + role.getCode() + "已经存在");
        }
        role.setState(0);
        role.setGmtCreate(LocalDateTime.now());
        baseMapper.insert(role);
    }

    /**
     * 角色授权资源
     *页面选中下一级会自动选择上级
     * @param roleId
     * @param resourceId
     */
    @Override
    public void toRoleAuth(Integer roleId, Integer[] resourceId) {
        //判断是否是超级管理员角色，如果是管理员角色不允许操作
        Set<String> roles = SubjectUtil.getPrincipal(LoginUser.class).getRoles();
        if (!roles.contains("superadmin")) {
            throw new ServiceException("非超级管理员不能操作");
        }
        Arrays.asList(resourceId).forEach(resource -> {
            if(StringUtil.isNull(roleAndResourceRelationMapper.selectAll(roleId,resource))) {
                roleAndResourceRelationMapper.insert(new RoleAndResourceRelation(roleId, resource));
            }
        });
    }

    /**
     * 角色解绑资源
     */
    @Override
    public  void updateAuth(Integer roleId, Integer[] resourceId){
        //判断是否是超级管理员角色，如果是管理员角色不允许操作
        Set<String> roles = SubjectUtil.getPrincipal(LoginUser.class).getRoles();
        if (!roles.contains("superadmin")) {
            throw new ServiceException("非超级管理员不能操作");
        }
        roleAndResourceRelationMapper.removeByIds(roleId,resourceId);
    }

    /**
     * 修改角色信息
     */
    @Override
    public void updateById(Role role) {
        List<Role> lists = baseMapper.selectAll();
        lists.forEach(list -> {
            if (role.getName().equals(list.getName()) && !role.getId().equals(list.getId())) {
                throw new ServiceException("角色名已存在");
            }
            if (role.getCode().equals(list.getCode()) && !role.getId().equals(list.getId())) {
                throw new ServiceException("角色识别号已存在");
            }
        });
        baseMapper.updateById(role);
    }

    /**
     * 用户角色更新
     */
    @Override
    public void updateUserRole(Integer userId, Integer[] roleId) {
        userAndRoleRelationMapper.deleteById(userId);
        Arrays.asList(roleId).forEach(role -> {
            userAndRoleRelationMapper.insert(new UserAndRoleRelation(userId, role));
        });
    }


    /**
     * 查询用户所有角色
     * @param userId
     * @return
     */
    @Override
    public List<Map<Integer, Object>> selectRolesNameCodeIdByUserId(Integer userId) {
        return baseMapper.selectRolesNameCodeIdByUserId(userId);
    }


    /**
     * 删除角色
     *
     * @param ids
     */
    @Override
    public void removeByIds(Integer[] ids) {
        Arrays.asList(ids).forEach(id -> {
            long l = userAndRoleRelationMapper.selectCountByRoleId(id);
            if (l > 0) {
                throw new ServiceException("有绑定用户,不允许删除角色");
            }
            //删除角色资源表关联
            roleAndResourceRelationMapper.deleteByRoleId(id);
        });
        baseMapper.removeByIds(ids);
    }

    @Override
    public Role selectById(Integer id) {
        Role selectOne = baseMapper.selectById(id);
        if (StringUtil.isNull(selectOne)) {
            throw new ServiceException("信息不存在");
        }
        return selectOne;
    }

    /**
     * 查所有权限名
     */
    @Override
    public List<Map<Integer, Object>> selectAllRoleNameAndId() {
        return baseMapper.selectAllRole();
    }

}
